package com.yzyz.management.web;

import java.io.IOException;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.sf.json.JSONArray;
import net.sf.json.JsonConfig;

import org.springframework.web.servlet.mvc.multiaction.MultiActionController;

import com.yzyz.bean.route.RouteGroupBean;
import com.yzyz.service.RouteGroupService;
import com.yzyz.utils.error.ErrorBean;
import com.yzyz.utils.error.Error;

/**
 * 
 * @author David Sun
 * @Date   2010-4-6
 *
 */
public class RouteGroupController extends MultiActionController {
	private RouteGroupService routeGroupService;

	public void setRouteGroupService(RouteGroupService routeGroupService) {
		this.routeGroupService = routeGroupService;
	}
	
	/**
	 * 获取线路板块或者分组
	 * @param request
	 * @param response
	 * @throws IOException 
	 */
	public void getRouteGroups(HttpServletRequest request, HttpServletResponse response) throws IOException{
		List<RouteGroupBean> groups = this.routeGroupService.paginate(Integer.valueOf(request.getParameter("start")), Integer.valueOf(request.getParameter("limit")));
		JsonConfig config = new JsonConfig();
		config.setExcludes(new String[]{"date","available","level"});
		JSONArray arr = JSONArray.fromObject(groups, config);
		StringBuilder sb = new StringBuilder();
		sb.append("{\"sum\":").append("\""+this.routeGroupService.getCount()+"\",");
		sb.append("\"data\":").append(arr.toString());
		sb.append("}");
		this.writeToClient(response, sb.toString());
	}
	
	/**
	 * 添加线路板块
	 * @param request
	 * @param response
	 * @throws IOException
	 */
	public void add(HttpServletRequest request, HttpServletResponse response) throws IOException{
		RouteGroupBean group = new RouteGroupBean();
		group.setName(request.getParameter("name"));
		this.routeGroupService.add(group);
		ErrorBean error = ErrorBean.getInstance(Error.SUCCESS,"添加成功", group.getId());
		this.writeToClient(response, error.toJson());
	}
	
	/**
	 * 
	 * @param request
	 * @param response
	 * @throws IOException 
	 */
	public void update(HttpServletRequest request, HttpServletResponse response) throws IOException{
		RouteGroupBean group = new RouteGroupBean();
		group.setName(request.getParameter("name"));
		group.setId(Integer.valueOf(request.getParameter("groupId")));
		this.routeGroupService.update(group);
		this.writeToClient(response, ErrorBean.getSuccessMsg());
	};
	
	private void writeToClient(HttpServletResponse response, String contents) throws IOException {
		response.setHeader("Cache-Control", "no-cache");
		response.setHeader("Programa", "no-cache");
		response.setDateHeader("Expires", -1L);
		response.setContentType("text/html; charset=UTF-8");
		response.getWriter().write(contents);
		response.flushBuffer();
		response.getWriter().close();
	}
	
	
}
